package main

import (
	"fmt"
	"go-chromedp-client/app"
	"go-chromedp-client/util"
	"net/url"
	"os"
	"path/filepath"
	"runtime"
	"time"

	fyneapp "fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/container"

	//"fyne.io/fyne/v2/internal/driver/mobile"

	"fyne.io/fyne/v2/widget"
	"github.com/joho/godotenv"
)

func main() {
	ROOT_PATH, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		panic(err)
	}
	if runtime.GOOS == "android" {
		ROOT_PATH = "/storage/emulated/0/cybercore"
	}
	// 从配置文件读取配置
	loadserr := godotenv.Load(ROOT_PATH + string(os.PathSeparator) + "config.env")
	if loadserr != nil {
		fmt.Println(loadserr)
	}
	if runtime.NumCPU() > 1 {
		runtime.GOMAXPROCS(runtime.NumCPU() - 1)
	}
	fmt.Println(ROOT_PATH + string(os.PathSeparator) + "config.env")
	fmt.Println(ROOT_PATH)

	fmt.Println("小说下载工具")
	fmt.Println("可加QQ群聊:590985689")
	fmt.Println("邮箱:sumroads@foxmail.com")
	fmt.Println(os.Getenv("ROUTE"))

	http_port := os.Getenv("http_port")
	if http_port == "" {
		http_port = "8091"
	}
	fmt.Println("可打开此网站使用: http://localhost:" + http_port)

	_, err = os.Stat(ROOT_PATH)
	if err != nil && os.IsNotExist(err) {
		os.MkdirAll(ROOT_PATH, 0777)
	}
	dir := ROOT_PATH + "/web"
	_, err = os.Stat(dir)
	if err != nil && os.IsNotExist(err) {
		os.MkdirAll(dir, 0777)
	}
	dir = ROOT_PATH + "/web/output"
	_, err = os.Stat(dir)
	if err != nil && os.IsNotExist(err) {
		os.MkdirAll(dir, 0777)
	}
	os.Setenv("ROOT_PATH", ROOT_PATH)
	functions := os.Getenv("Function")
	if functions == "" {
		os.Setenv("Fuction", "Get,get,GET,Post,post,POST,ChromeGet,SingleGet,ExistGet,ProcessGet,HostGet,HostExistGet")
	}

	//一些定时任务
	go func() {

		t1 := time.Tick(30 * time.Second)
		for {
			<-t1

		}
	}()

	go app.HttpServer()

	a := fyneapp.NewWithID("main")
	w := a.NewWindow("赛博核")
	ip, err := util.GetInternalIP()
	if err != nil {
		ip = "127.0.0.1"
	}
	hello := widget.NewRichTextWithText(runtime.GOOS + " Path: " + a.Storage().RootURI().Path())
	host := widget.NewLabel("LC: http://127.0.0.1:" + http_port)
	ipl := widget.NewLabel("IP: http://" + ip + ":" + http_port)
	e := util.FilePutContent(ROOT_PATH+"/time.txt", "你好:"+util.GetDate(), false)
	txt := "ok:" + ROOT_PATH
	if e != nil {
		txt = e.Error()
	}
	hoste := widget.NewTextGridFromString(txt)
	vtext := widget.NewLabel("V:1.0.3")
	w.SetContent(container.NewVBox(
		hello,
		host,
		ipl,
		hoste,
		widget.NewButton("GO LC", func() {
			r, _ := url.Parse("http://127.0.0.1:8091")
			a.OpenURL(r)
		}),
		widget.NewButton("GO IP", func() {
			r, _ := url.Parse("http://" + ip + ":8091")
			a.OpenURL(r)
		}),
		widget.NewButton("Follow Sumroads", func() {
			r, _ := url.Parse("https://space.bilibili.com/34836478")
			a.OpenURL(r)
		}),
		// widget.NewButton("check version", func() {
		// 	r, _ := url.Parse("https://spider.sumroads.site")
		// 	a.OpenURL(r)
		// }),
		vtext,
	))
	//测试
	w.ShowAndRun()

}
